import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ViewController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { AlertController } from 'ionic-angular';
import { TranslateService } from '@ngx-translate/core';

import { HomePage } from '../home/home';
import { CurrentOrderPage } from '../current-order/current-order';
import { HelperService } from "../../providers/services.helper";
import { ApiService } from "../../providers/services.api";
import { GlobalData } from "../../providers/GlobalData";

/**
 * Generated class for the TableListPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-table-list',
  templateUrl: 'table-list.html',
})
export class TableListPage {

  type: string;
  activeTable: number;
  home: any = HomePage;
  curTableNum: number;
  curTableId: number;
  tableListTitle: string;

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    private storage: Storage,
    public viewCtrl: ViewController,
    public alertCtrl: AlertController,
    public translate: TranslateService,
    private helperService: HelperService,
    public api: ApiService,
    public global: GlobalData) {

    this.type = this.navParams.get('type');

    if (this.type == 'newTable') {
      this.tableListTitle = 'TABLE';
    } else {
      this.tableListTitle = 'TRANSFER_CURRENT_TABLE';
    }

    console.log(this.type, this.global.curCart.table_num, this.global.tableList);

    if (isNaN(+this.global.curCart.table_num)) {
      this.curTableId = Number(this.global.curCart.table_num.substring(0, this.global.curCart.table_num.length - 1));
    } else {
      this.curTableId = Number(this.global.curCart.table_num);
    }
    console.log('curTableId:', this.global.tableList[this.curTableId - 1], 'isNaN:', isNaN(+this.global.curCart.table_num));
  }

  // click table
  tableClick(i) {
    if (this.type == 'newTable') {
      for (let table of this.global.tableList) {
        table.collapsed = true;
      }
      if (this.activeTable != i) {
        this.global.tableList[i].collapsed = false;
        this.activeTable = i;
      }
      else {
        this.global.tableList[i].collapsed = true;
        this.activeTable = null;
      }
    }
    if (this.type == 'switchTable') {
      // if (i != 0 && this.curTableId == (i - 1)) {
      //   this.viewCtrl.dismiss(null);
      //   return;
      // }
      console.log(i);

      var table_no: string;
      if (i != 0 && this.global.tableList[i]['shared']) {
        for (let share of this.global.tableList[i]['shared']) {
          if (share['invoice_no'] == null || share['invoice_no'] == '') {
            table_no = share['name'];
            break;
          }
        }
      }
      console.log('set table_no:' + table_no);

      if (i == 0) {
        table_no = '0';
      }

      let alert = this.alertCtrl.create({
        title: this.translate.instant('CONFIRM_SWITCH_TABLE_TITLE'),
        message: this.translate.instant('CONFIRM_SWITCH_TABLE_CONTENT', {
          fromTable: this.global.curCart.table_num == 0 ? this.translate.instant('TAKE_AWAY') : this.global.curCart.table_num,
          toTable: table_no == '0' ? this.translate.instant('TAKE_AWAY') : table_no
        }),
        buttons: [
          {
            text: this.translate.instant('CANCEL'),
            role: 'cancel',
            handler: () => {
              console.log('Cancel clicked');
            }
          },
          {
            text: this.translate.instant('CONFIRM'),
            handler: () => {
              console.log('switch table Confirm clicked');
              this.helperService.showLoading();
              this.setTable(table_no, this.global.curCart.id).then(cart => {
                this.helperService.hideLoading();
                this.global.curCart = cart['data'];
                this.viewCtrl.dismiss(null);
              }, error => {
                this.helperService.hideLoading();
              });
            }
          }
        ]
      });
      alert.present();
    }
  }

  newCart(table_num) {
    return new Promise((resolve, reject) => {
      this.storage.get('settings').then(setting => {
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('locale', setting.locale);
        urlSearchParams.append('token', setting.token);
        urlSearchParams.append('check_out_warehouse_id', setting.warehouse_id);
        urlSearchParams.append('user_id', this.global.curMember.user_id == 0 ? null : this.global.curMember.user_id);
        this.api.newCart(urlSearchParams.toString()).then(data => {
          console.log('newCart success:', data);
          resolve(data['invoice_id']);
        }, error => {
          console.log('newCart error:', error);
          this.helperService.showToast(error);
          reject(error);
        });
      });
    });
  }

  setTable(table_num, invoice_id) {
    return new Promise((resolve, reject) => {
      this.storage.get('settings').then(setting => {
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('locale', setting.locale);
        urlSearchParams.append('token', setting.token);
        urlSearchParams.append('warehouse_id', setting.warehouse_id);
        urlSearchParams.append('action', 'read');
        urlSearchParams.append('invoice_id', invoice_id);
        urlSearchParams.append('table_num', table_num);
        urlSearchParams.append('calling_type', 'f_b');
        this.api.setCart(urlSearchParams.toString()).then(cart => {
          console.log('setTable success:', cart);
          resolve(cart);
        }, (error) => {
          console.log('setTable error:', error);
          this.helperService.showToast(error);
          reject(error);
        });
      });
    });
  }

  getTableNoById(tableId) {
    for (var j = 0; j < this.global.tableList.length; j++) {
      if (this.global.tableList[j].id == tableId) {
        if (this.global.tableList[j].share) {
          for (var k = 0; k < this.global.tableList[j].share.length; k++) {
            if (this.global.tableList[j].share[k].invoice_no == this.global.curCart.id) {
              return this.global.tableList[j].share[k].name;
            }
          }
        }
      }
    }
  }

  loadOrder(order) {
    console.log('load order:', order);
    this.viewCtrl.dismiss(order);

  }

  // open new order with table no.
  newOrder() {
    this.helperService.showLoading();
    var table_no: string;
    if (this.global.tableList[this.activeTable]['shared']) {
      for (let share of this.global.tableList[this.activeTable]['shared']) {
        if (share['invoice_no'] == null || share['invoice_no'] == '') {
          table_no = share['name'];
          break;
        }
      }
    }
    console.log('activeTable:', this.activeTable, 'setTableNum:', table_no);
    this.newCart(0).then(invoiceId => {
      this.setTable(table_no, invoiceId).then(cart => {
        this.helperService.hideLoading();
        this.global.tableList[this.activeTable].orders.push({
          table_num: cart['data']['table_num'],
          data: {
            id: cart['data']['id'],
            table_num: cart['data']['table_num'],
            invoice_date: cart['data']['invoice_date'],
            invoice_no: cart['data']['invoice_no'],
            name: cart['data']['customer_name'],
            price: '0',
            served_qty: '0/0'
          }
        });
        for (let share of this.global.tableList[this.activeTable]['shared']) {
          if (share['name'] == table_no) {
            share['invoice_no'] = cart['data']['id'];
            break;
          }
        }
      });
    }, error => {
      this.helperService.hideLoading();
    });
  }

  // dismiss table list modal
  dismiss() {
    this.viewCtrl.dismiss(null);
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad TableListPage');
  }

}
